﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GameSchool.Models;
using GameSchool.ViewModels;
using System.Web.Security;
using System.Web.Profile;


namespace GameSchool.Controllers
{
	public class AssignmentController : Controller
	{
		AssignmentRepository repository = new AssignmentRepository();
		LevelRepository levelRep = new LevelRepository();
		// GameRegistrationRepository gameReg = new GameRegistrationRepository();

		public ActionResult Index()
		{
			return View();
		}

		// Skila lista af öllum verkefnum
		public ActionResult assignments(int? id)
		{
			var items = from n in repository.Assignments()
						orderby n.ID
						select n;
			return View(items);
		}

		/* Aðeins umsjónarmaður og kennari
		 * Hér fyrir neðan eru 2 create controllerar og 2 edit controllerar.
		 * Þeir sjá um að birta formið "AssignmentForm.cshtml"
		 */

		// Nær í formið þegar búa á til nýtt verkefni
		[HttpGet]
		[Authorize(Roles = "Admin, Teacher")]
		public ActionResult createAssignment(int id)
		{
			ViewData["currGame"] = id;	// Senda gameId í viewið

			// Finna öll borð sem tilheyra þessum leik
			var levels = (from n in levelRep.Levels()
						  where n.GameID == id
						  select n);
			// Og senda þau svo í selectlista sem verður birtur í dropdown-lista í viewinu
			ViewData["listOfLevels"] = new SelectList(levels, "ID", "Title");

			// Búa til valmöguleika fyrir það hvort birta á verkefnið
			var items = new List<SelectListItem>();
			items.Add(new SelectListItem() { Selected = true, Text = "Já", Value = "1" });
			items.Add(new SelectListItem() { Selected = false, Text = "Nei", Value = "0" });
			ViewData["visible"] = new SelectList(items, "Value", "Text");
			TempData["currUrl"] = ("/Game/ViewGame/" + id).ToString();
			return View(new Assignment());
		}

		// Póstar forminu þegar búa á til nýtt verkefni
		[HttpPost]
		[Authorize(Roles = "Admin, Teacher")]
		public ActionResult createAssignment(FormCollection formData)
		{
			Assignment newAssignment = new Assignment();
			newAssignment.Date = DateTime.Now;
			repository.Add(newAssignment);
			UpdateModel(newAssignment);
			repository.Save();

			return Redirect("../.." + TempData["currUrl"]);
		}

		// Nær í formið þegar á að breyta verkefni
		[HttpGet]
		[Authorize(Roles = "Admin, Teacher")]
		public ActionResult editAssignment(int? id)
		{
			ViewData["currGame"] = id;	// Senda gameId í viewið

			// Finna öll borð sem tilheyra þessum leik
			var levels = (from n in levelRep.Levels()
						  where n.GameID == id
						  select n);
			// Og senda þau svo í selectlista sem verður birtur í dropdown-lista í viewinu
			ViewData["listOfLevels"] = new SelectList(levels, "ID", "Title");

			// Búa til valmöguleika fyrir það hvort birta á verkefnið
			var items = new List<SelectListItem>();
			items.Add(new SelectListItem() { Selected = true, Text = "Já", Value = "1" });
			items.Add(new SelectListItem() { Selected = false, Text = "Nei", Value = "0" });
			ViewData["visible"] = new SelectList(items, "Value", "Text");

			TempData["currUrl"] = ("/Game/ViewGame/" + id).ToString();

			var item = (from n in repository.Assignments()
						where n.ID == id.Value
						select n).SingleOrDefault();

			if (item != null)
			{
				return View(item);
			}
			else
			{
				// TODO: Ath hvert á að redirecta...
				return RedirectToAction("Index");
			}
		}

		// Póstar breyttu verkefni
		[HttpPost]
		[Authorize(Roles = "Admin, Teacher")]
		public ActionResult editAssignment(int? id, FormCollection formData)
		{
			var item = (from n in repository.Assignments()
						where n.ID == id.Value
						select n).SingleOrDefault();

			if (item != null)
			{
				//Geri breytingar
				UpdateModel(item);

				//Vista breytingar
				repository.Save();

				return Redirect("../.." + TempData["currUrl"]);
			}
			else
			{
				return View();
			}
		}


		[HttpGet]
		public ActionResult viewAssignment(int? id)
		{
			var UserId = new Guid(Membership.GetUser(HttpContext.User.Identity.Name).ProviderUserKey.ToString());
			AssignmentRepository a = new AssignmentRepository();
			AssignmentSolutionRepository aSol = new AssignmentSolutionRepository();
			var model = new ViewAssignmentViewModel
			{
				// Finna rétt verkefni
				Assignment = (from n in repository.Assignments()
						 where n.ID == id.Value
						 select n).SingleOrDefault(),

				// Velja allar lausnir sem hafa verið sendar inn
				AssignmentSolutions = (from n in aSol.AssignmentSolutions()
										where n.AssignmentID == id
										select n),
				
				// Finna lausn þess nemanda sem er innskráður
				AssignmentSolution = (from n in aSol.AssignmentSolutions()
									   where n.AssignmentID == id
									   where n.UserID == UserId
									   select n).FirstOrDefault(),
				
				gameID = id.Value,

			};
			return View(model);
		}

		// Skoða lausn nemanda
		[HttpGet]
		public ActionResult ViewAssignmentSolution(int? id)
		{
			AssignmentSolutionRepository aSol = new AssignmentSolutionRepository();
			var model = new ViewAssignmentViewModel
			{
				AssignmentSolution = (from n in aSol.AssignmentSolutions()
							  where n.ID == id
							  select n).FirstOrDefault(),
			};
			return View(model);
		}

		// Þetta keyrir ef kennari eða umsjónarmaður er að skoða lausn notanda og gefur einkunn fyrir lausnina
		[HttpPost]
		public ActionResult ViewAssignmentSolution(int? id, double grade)
		{
			AssignmentSolutionRepository aSol = new AssignmentSolutionRepository();
			var model = new ViewAssignmentViewModel
			{
				AssignmentSolution = (from n in aSol.AssignmentSolutions()
									  where n.ID == id
									  select n).FirstOrDefault(),
			};

			// Vista einkunnina
			model.AssignmentSolution.Grade = grade;

			if (model != null)
			{
				//Geri breytingar
				UpdateModel(model);

				//Vista breytingar
				aSol.Save();

				return View(model);
			}
			else
			{
				return View();
			}
		}
	}
}